package twilight.companion.entity.ai;

import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.goal.MeleeAttackGoal;
import net.minecraft.world.phys.Vec3;
import twilight.companion.entity.MiniYetiEntity;

public class MiniYetiThrowRiderGoal extends MeleeAttackGoal {
    private int throwTimer;
    private int timeout;
    private int cooldown;
    private final MiniYetiEntity miniYeti;

    public MiniYetiThrowRiderGoal(MiniYetiEntity creature, double speedIn, boolean useLongMemory) {
        super(creature, speedIn, useLongMemory);
        this.miniYeti = creature;
    }

    @Override
    public boolean canUse() {
        return this.mob.getPassengers().isEmpty() && this.mob.getTarget() != null && super.canUse();
    }

    @Override
    public void start() {
        this.throwTimer = 10 + this.mob.getRandom().nextInt(20);
        this.timeout = 60 + this.mob.getRandom().nextInt(20);
        super.start();
    }

    @Override
    public void tick() {
        this.timeout--;
        if (!this.mob.getPassengers().isEmpty())
            this.throwTimer--;
        else
            super.tick();
    }

    @Override
    protected void checkAndPerformAttack(LivingEntity victim, double distance) {
        double d0 = this.getAttackReachSqr(victim);

        if (distance <= d0 && this.getTicksUntilNextAttack() <= 0 && this.mob.getPassengers().isEmpty() && this.cooldown-- == 0) {
            this.cooldown = 3;
            this.resetAttackCooldown();
            this.mob.swing(InteractionHand.MAIN_HAND);
            if (this.mob.getPassengers().isEmpty()) {
                victim.stopRiding();
                victim.startRiding(this.mob, true);
            }
        }
    }

    @Override
    public void stop() {
        if (!this.mob.getPassengers().isEmpty()) {
            Entity rider = this.mob.getPassengers().get(0);
            rider.stopRiding();

            Vec3 throwVec = new Vec3(this.mob.getLookAngle().x() * 1.5D, 0.6, this.mob.getLookAngle().z() * 1.5D);
            rider.push(throwVec.x(), throwVec.y(), throwVec.z());
        }
        super.stop();
    }

    @Override
    public boolean canContinueToUse() {
        return (this.throwTimer > 0 && !this.mob.getPassengers().isEmpty()) || 
        (this.timeout > 0 && super.canContinueToUse() && this.mob.getPassengers().isEmpty());
    }
}